<?php

/**
 * 微信事件回复
 * 
 * Apps/Common/Service/WxEventService.class.php
 * Zix @ 2015-07-16
 */

namespace Common\Service;

use Common\Service\MerUserService;
use Common\Service\WxTextReplyService;

class WxEventService {
  private static $instance;

  var $mer_id ;
  var $wx_id ;
  var $openid ;
  var $data ;
  var $wechat ;
  
  public static function instance() {
    if (self::$instance == null) {
      $instance = new WxEventService();
    }
    return $instance;
  }

  function response( $mer_id , $wx_id ,  $data , $wechat ) {
    $this->mer_id = $mer_id ;
    $this->wx_id = $wx_id ;
    $this->data = $data ;
    $this->openid = $data['FromUserName'];
    $this->wechat = $wechat ;
    
    $func = strtolower( $data['event'] ) ;
    if ( method_exists( 'WxEventService', $func ) ) {
      $this->$func();
    }
  }
  
  /**
   * 关注事件
   */
  function subscribe( $data ) {
    //检查openid是否存在
    $MerUser = MerUserService::instance();
    $user_data = $MerUser->get_by_mer_openid($this->mer_id, $this->openid );
    
    //用户已经
    if( !empty( $user_data ) ) {
      //回复关注消息
      $this->_reply_subscribe();
      return ;
    }
    
    //用户不存在
    //检查是否带场景的二维码
    $pid = 0 ;
    if( isset($data['EventKey']) ) {
      $pid = $data['EventKey'] ;
    }
    
    //创建用户
    $MerUser->create_by_openid( $this->mer_id , $this->wx_id , $this->openid , $pid );
    
    //回复关注消息
    $this->_reply_subscribe();
  }
  
  /**
   * 关注回复
   */
  function _reply_subscribe() {
    $WxTextReply = WxTextReplyService::instance();
    $ret_text = $WxTextReply->get_subscribe( $this->mer_id , $this->wx_id );
    if ( !empty( $ret_text ) ) {
      //回复图文消息
      $this->wechat->replyText( $ret_text );
    }
  }


  /**
   * 取消关注事件
   */
  function unsubscribe( $data ) {
    
  }
  
  function scan() {
    
  }
  
  function click() {
    
  }
  
  function location() {
    
  }
  
  //链接
  function view() {
    
  }
}
